// pages/quality-active/index.js
import { toPrevPage } from "../../../utils/util";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    types: [],
    type: "",
    typeName: "",
    quality_code: "", // 质保卡编号
    contcat_name: "",
    contcat_phone: "",
    merchant_id: "",
    merchant_name: "",
    nameIsError: "",
    phoneIsError: "",
    merchantIsError: "",
    swi_num: "",
    merchants: [],
    zbk_img: [],
    az_img: [],
    fileList: [],
    azFileList:[],
  },

  getMerchants() {
    const params = { type: "7" };

    wx.ajax
      .post("queryUserSubscribeMerchant.action", params, false)
      .then((res) => {
        // console.log(res);
        if (res.success) {
          this.setData({
            merchants: res.result,
          });
        }
      });
  },

  getTypes() {
    wx.ajax.post("queryProductBxqsetList.action", {}, false).then((res) => {
      if (res.success) {
        // console.log(res);
        this.setData({
          types: res.result,
        });
      }
    });
  },

  afterRead(event) {
    const image = event.detail.file;

    wx.ajax.uploadFile({
      filePath: image.url,
      callback: (url) => {
        if (url) {
          const { fileList, zbk_img } = this.data;

          fileList.push(url);
          zbk_img.push(image);

          this.setData({
            zbk_img,
            fileList,
          });
        }
      },
    });
  },
  afterAzImgRead(event) {
    const image = event.detail.file;

    wx.ajax.uploadFile({
      filePath: image.url,
      callback: (url) => {
        if (url) {
          const { azFileList, az_img } = this.data;

          azFileList.push(url);
          az_img.push(image);

          this.setData({
            az_img,
            azFileList,
          });
        }
      },
    });
  },
  handleDelete(event) {
    const image = event.detail.file;
    const { zbk_img, fileList } = this.data;
    let index;

    zbk_img.forEach((item, i) => {
      if (item.url === image.url) {
        index = i;
      }
    });

    zbk_img.splice(index, 1);
    fileList.splice(index, 1);

    this.setData({
      zbk_img,
      fileList,
    });
  },
  handleDeleteAz(event) {
    const image = event.detail.file;
    const { az_img, azFileList } = this.data;
    let index;

    az_img.forEach((item, i) => {
      if (item.url === image.url) {
        index = i;
      }
    });

    az_img.splice(index, 1);
    azFileList.splice(index, 1);

    this.setData({
        az_img,
      azFileList,
    });
  },
  handleValideCode(event) {
    const { value } = event.detail;

    this.setData({
      quality_code: value,
      codeIsError: value ? "" : "请输入质保卡编号",
    });
  },

  handleValideName(event) {
    const { value } = event.detail;

    this.setData({
      contcat_name: value,
      nameIsError: value ? "" : "请输入姓名",
    });
  },

  handleValidePhone(event) {
    const { value } = event.detail;

    this.setData({
      contcat_phone: value,
      phoneIsError: value ? "" : "请输入手机号",
    });
  },

  handleMerchantChange(event) {
    const { value } = event.detail;
    const { merchants } = this.data;

    this.setData({
      merchant_id: merchants[value]["id"],
      merchant_name: merchants[value]["merchant_name"],
      merchantIsError: value ? "" : "请选择店铺",
    });
  },

  handleTypeChange(event) {
    const { value } = event.detail;
    const { types } = this.data;

    this.setData({
      type: types[value]["id"],
      typeName: types[value]["name"],
    });
  },

  handleSubmit() {
    const {
      type,
      quality_code,
      contcat_name,
      contcat_phone,
      merchant_id,
      fileList,
      azFileList,
      swi_num,
    } = this.data;

    if (type === "0") {
      if (!quality_code) {
        this.setData({
          codeIsError: "请输入质保卡号",
        });

        return;
      }

      const param = { quality_code };

      wx.ajax.post("completeSGQualityInfo.action", param, true).then((res) => {
        if (res.success) {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 2000,
          });

          wx.navigateTo({
            url: "/quality/pages/quality-info/index?type=7",
          });

          // const timer = setTimeout(() => {
          //   toPrevPage();

          //   clearTimeout(timer);
          // }, 1000);
        } else {
          console.log(res);
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 2000,
          });
        }
      });
    } else if (type && type !== "0") {
      if (!contcat_name) {
        this.setData({
          nameIsError: "请输入姓名",
        });

        return;
      }

      if (!contcat_phone) {
        this.setData({
          phoneIsError: "请输入手机号",
        });

        return;
      }

      if (!merchant_id) {
        this.setData({
          merchantIsError: "请选择店铺",
        });

        return;
      }

      if (fileList && fileList.length === 0) {
        wx.showToast({
          title: "请上传图片",
          icon: "none",
          duration: 2000,
        });

        return;
      }

      const params = {
        bxqset_id: type,
        merchant_id,
        contcat_name,
        contcat_phone,
        swi_num,
        zbk_img: fileList.join(","),
        az_img: azFileList.join(","),
      };

      wx.ajax.post("addQualityInfo.action", params, true).then((res) => {
        // console.log(res);
        if (res.success) {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 2000,
          });

          wx.navigateTo({
            url: "/quality/pages/quality-info/index?type=7",
          });

          // const timer = setTimeout(() => {
          //   toPrevPage();

          //   clearTimeout(timer);
          // }, 1000);
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 2000,
          });
        }
      });
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getTypes();
    this.getMerchants();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});
